package main

import (
	"face-revive-task/entity/config"
	"face-revive-task/logic"
	"flag"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	host     string
	port     int
	user     string
	password string
)

func main() {
	flag.StringVar(&host, "host", "127.0.0.1", "mysql host")
	flag.IntVar(&port, "port", 3306, "mysql port")
	flag.StringVar(&user, "user", "root", "mysql user")
	flag.StringVar(&password, "password", "", "mysql password")
	flag.StringVar(&config.Token, "token", "", "token")
	flag.StringVar(&config.UploadUrl, "uploadUrl", "", "upload url")
	flag.StringVar(&config.DownloadDir, "downloadDir", "", "download dir")
	flag.StringVar(&config.DownloadUrl, "downloadUrl", "", "download url")
	flag.Parse()
	initDB()

	ticker := time.NewTicker(10 * time.Second)
	for _ = range ticker.C {
		logic.Do()
	}
	defer ticker.Stop()
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	o := <-sig
	log.Printf("recieve signal %s ,server will stop gracefully", o.String())
}

// https://github.com/go-sql-driver/mysql
// https://gorm.io/zh_CN/docs/connecting_to_the_database.html
func initDB() {
	dsn := "%s:%s@tcp(%s:%d)/user_db?charset=utf8mb4&parseTime=True&loc=Local&timeout=2s&readTimeout=60s&clientFoundRows=true"
	dsn = fmt.Sprintf(dsn, user, password, host, port)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			// 驼峰表名，不加s
			SingularTable: true,
		},
	})
	if err != nil {
		log.Fatalf("connect db errors:%s", err)
	}
	// 添加连接池
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatalf("connect db errors:%s", err)
	}
	sqlDB.SetMaxIdleConns(5)
	sqlDB.SetConnMaxLifetime(60 * time.Second)
	sqlDB.SetConnMaxIdleTime(60 * time.Second)
	sqlDB.SetMaxOpenConns(5)
	config.DbClient = db
}
